#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Tubemaster
#
# Copyright (C) 2009 Selim Ok <selimok@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# This is the tarball creator of Tubemaster

import shutil 
import os
import sys
import subprocess
import dircache

def recursive_delete(dirname):
    files = dircache.listdir(dirname)
    for file in files:
        path = os.path.join (dirname, file)
        if os.path.isdir(path):
            recursive_delete(path)
        else:
            retval = os.unlink(path)
    os.rmdir(dirname)


def cleanup():
    script_dir = os.path.join(os.getcwd(),os.path.dirname(sys.argv[0]))
    if script_dir[-2:] == '/.':
        script_dir = script_dir[:-2]
    try:
        temp_dir = os.path.join(script_dir,'tmp/')
        recursive_delete(temp_dir)
        print 'All temporary files cleaned successfully.'
    except:
        print '*** An exception occured during cleaning process. ***'
        sys.exit(-1)

print 'Tubemaster Tarball Creator'

script_dir = os.path.join(os.getcwd(),os.path.dirname(sys.argv[0]))
if script_dir[-2:] == '/.':
    script_dir = script_dir[:-2]


temp_dir = os.path.join(script_dir,'tmp/')
tarball_dir = os.path.join(temp_dir,'tubemaster/')

try:
    print 'Creating temporary directory...'
    os.mkdir(temp_dir)
except:
    print '*** An exception occured. Please remove the ./tmp/ directory first. ***'
    cleanup()
    sys.exit(-1)

try:
    print 'Creating tarball directory...'
    os.mkdir(tarball_dir)
    os.mkdir(tarball_dir+'src')
    os.mkdir(tarball_dir+'data')
    os.mkdir(tarball_dir+'bin')
except:
    print '*** An exception occured. Please remove the ./tmp/tubemaster/ directory first. ***'
    cleanup()
    sys.exit(-1)

tarball_elements = [
'src/constants.py',
'src/converter.py',
'src/fetcher.py',
'src/getdownloadurl.py',
'src/getoriginaltitle.py',
'src/notifications.py',
'src/preferences.py',
'src/tubemaster.py',
'src/ui_about.py',
'src/ui_main.py',
'src/ui_preferences.py',
'data/abort.png',
'data/download.png',
'data/gettitle.png',
'data/pause.png',
'data/resume.png',
'data/tubemaster-24x24.png',
'data/tubemaster-32x32.png',
'data/tubemaster-48x48.png',
'data/tubemaster-84x84.png',
'data/tubemaster.desktop',
'bin/tubemaster',
'AUTHORS',
'COPYING',
'INSTALL',
'install.py',
'README',
'RELEASE'
]


try:
    print 'Copying files ...'
    for x in tarball_elements:
        shutil.copy(os.path.join(script_dir,x),os.path.join(tarball_dir,x))
except:
    print '*** An exception occured. Exiting... ***'
    cleanup()
    sys.exit(-1)


print 'Creating tarball ...'

#Change current working directory
os.chdir(temp_dir)
tarball = subprocess.Popen('tar -czvf tubemaster.tar.gz tubemaster/',
                                shell=True, 
                                stdin=None,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                            )
stdout = tarball.stdout.readlines()
stderror = tarball.stderr.readlines()

#Change current working directory
os.chdir(script_dir)

if (stderror.__len__()>0):
    print '*** An unknown error occured during creating tarball! Exiting... ***'
    cleanup()
    sys.exit(-1)
else:
    try:
        shutil.move(os.path.join(temp_dir,'tubemaster.tar.gz'),script_dir)
        print 'Moving tarball to the script directory...'
    except:
        print '*** An unknown error occured during moving tarball! Exiting... ***'
        cleanup()
        sys.exit(-1)

print 'Cleaning up temporary files...'
cleanup()
print 'Tubemaster tarball created succesfully!'


